package com.putaoshu.ptp;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Component
public class P2pPointClient {
    private Logger logger = LoggerFactory.getLogger(P2pPointClient.class);
    private String wsUrl = "ws://localhost:7001";
    private List<WebSocket> localsockets = new ArrayList<WebSocket>();
    public List<WebSocket> getLocalsockets()
    {
        return localsockets;
    }
    public void setLocalsockets(List<WebSocket> localsockets)
    {
        this.localsockets = localsockets;
    }
    // 连接到服务端
    @PostConstruct
    @Order(2)
    public void connectPeer()
    {
        try{
            //创建webSOCKET客户端
            final WebSocketClient socketClient=new WebSocketClient(new URI(wsUrl)) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                sendMessage(this,"北京客户端成功创建客户端");
                    localsockets.add(this);
                }

                @Override
                public void onMessage(String s) {
                logger.info("北京客户端成功收到北京服务端发来的消息:"+s);
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                logger.info("北京客户端关闭");
                localsockets.remove(this);
                }

                @Override
                public void onError(Exception e) {
                    logger.info("北京客户端报错");
                    localsockets.remove(this);

                }

            };
            socketClient.connect();
        }catch (Exception e)
        {
            logger.info(e.toString());
        }
    }
    public void sendMessage(WebSocket socket,String message)
    {
        logger.info("发送给"+socket.getRemoteSocketAddress().getPort()+"的消息"+message);
        socket.send(message);
    }
    //向所有连接过的服务端广播消息
    public void broadcast(String message)
    {
        if(localsockets.size()==0|| StringUtils.isEmpty(message))
        {
            return;
        }
        logger.info("Glad to say broadcast to clients being started");
        for(WebSocket socket:localsockets)
        {
            this.sendMessage(socket,message);
        }
        logger.info("Glad to say braodcast to clients has  overred");
    }
}
